<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/8/17 15:36
 * Desc: 请求验证基础
 */
class Request_Api_V2_Base
{
    protected $validation;

    protected $request_param;

    protected $rules;

    public function __construct($request_param)
    {

        $this->validation    = Validation::factory($request_param);
        $this->request_param = $request_param;

    }

    /**
     * 验证参数并抛出错误
     * @return void
     * @throws Exception
     */
    public function check()
    {
        $this->make_rule();

        if (!$this->validation->check()) {
            $errors = $this->validation->errors('api');
            $keys   = array_keys($errors);
            throw new Exception(__("{$errors[$keys[0]]}"));
        }
    }

    public function make_rule()
    {
        foreach ($this->rules as $item) {
            foreach ($item[1] as $v) {
                if (is_array($v)) {
                    $this->validation->rule($item[0], $v[0], $v[1]);
                } else {
                    $this->validation->rule($item[0], $v);
                }
            }
        }
    }

    /**
     * 返回最小值规则
     * @param $number
     * @return array
     */
    public function rule_min($number): array
    {
        return ['min', [':value', $number]];
    }

    /**
     * 返回最大值规则
     * @param $number
     * @return array
     */
    public function rule_max($number): array
    {
        return ['max', [':value', $number]];
    }

    /**
     * 返回数组规则
     * @param $arr
     * @return array
     */
    public function rule_in_array($arr): array
    {
        return ['in_array', [':value', $arr]];
    }

    /**
     * 返回日期格式化规则
     * @param $format
     * @return array
     */
    public function rule_date_format($format): array
    {
        return ['date_format', [':value', $format]];
    }

    /**
     * 最小长度
     * @param $length
     * @return array
     */
    public function rule_min_length($length): array
    {
        return ['min_length', [':value', $length]];
    }

    /**
     * 最大长度
     * @param $length
     * @return array
     */
    public function rule_max_length($length): array
    {
        return ['max_length', [':value', $length]];
    }

}